const { join, extname } = require('path')
const url = require('url')
const qs = require('querystring')
const mimes = require('./lib/mime')
const fs = require('fs')
const http = require('http')


const rootpath = join(__dirname, 'www')
http.createServer((req, res) => {
    let { pathname, query } = url.parse(req.url, true)

    if (req.method === "POST") {
        if (pathname == '/upload') {
            let filename = Date.now() + extname(req.headers.filename)
            req.pipe(fs.createWriteStream(join(rootpath, 'uploads', filename)))
            res.end(JSON.stringify({ code: 0, url: 'http://localhost:3000/uploads/' + filename }))
        }
        else if(pathname=='/del'){
            let delpath=join(rootpath,'uploads',`${req.headers.delname}`)
            // console.log(delpath)
            fs.unlink(delpath, err => console.log(err))
        }
    }
    else {
        if (req.url !== "./favicon.ico") {
            let errpath = join(rootpath, "./404.html")

            pathname = pathname === '/' ? './index.html' : pathname
            let filename = join(rootpath, pathname)
            if (fs.existsSync(filename)) {
                //获得扩展名
                const ext = extname(filename).slice(1)
                const mime = mimes[ext]

                //设置相应的响应头
                // res.setHeader('content-type',mime)
                //获取get传输的数据
                let html
                if (ext === 'html') {
                    html = fs.readFileSync(filename, 'utf-8')
                    html = html.replace(/\{\{\s*(\w+)\s*\}\}/g, function (preg, match) {
                        return query[match]
                    })
                } else {
                    html = fs.readFileSync(filename)
                }
                res.end(html)
            } else {
                res.statusCode = 404
                res.end(fs.readFileSync(errpath))
            }
        }
    }
}).listen(3000, '0.0.0.0')